package com.xique.door.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xique.common.core.text.Convert;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.datascope.annotation.NeedSetFieldValue;
import com.xique.door.bean.dao.*;
import com.xique.door.bean.domain.BuildHouse;
import com.xique.door.bean.domain.BuildHouseUser;
import com.xique.door.bean.domain.BuildHouseV1;
import com.xique.door.bean.domain.User;
import com.xique.door.bean.request.RentStatisticRequest;
import com.xique.door.bean.request.buildHouse.BuildHouseSearchRequest;
import com.xique.door.bean.search.AreaBuildingHouseSearch;
import com.xique.door.bean.search.build.HouseListSearch;
import com.xique.door.bean.vo.SimpleHouseVo;
import com.xique.door.bean.vo.area.AreaBuildingHouseVo;
import com.xique.door.mapper.BuildHouseMapper;
import com.xique.door.mapper.BuildHouseMapperV1;
import com.xique.door.mapper.BuildHouseUserMapper;
import com.xique.door.service.IBuildHouseService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 房屋Service业务层处理
 *
 * @author caogq
 * @date 2021-09-09
 */
@Service
public class BuildHouseServiceImpl extends ServiceImpl<BuildHouseMapperV1, BuildHouseV1>
    implements IBuildHouseService {
  @Autowired private BuildHouseMapper buildHouseMapper;

  @Autowired private BuildHouseUserMapper buildHouseUserMapper;

  @Autowired private BuildHouseMapperV1 buildHouseMapperV1;

  /**
   * 查询房屋
   *
   * @param id 房屋ID
   * @return 房屋
   */
  @Override
  public BuildHouse selectBuildHouseById(Long id) {
    return buildHouseMapper.selectBuildHouseById(id);
  }

  @Override
  public List<BuildHouse> selectBuildHouseByIds(List<Long> ids) {
    return buildHouseMapper.selectBuildHouseByIds(ids);
  }

  /**
   * 查询房屋列表
   *
   * @param buildHouse 房屋
   * @return 房屋
   */
  @Override
  @NeedSetFieldValue
  public List<BuildHouse> selectBuildHouseList(BuildHouse buildHouse) {
    return buildHouseMapper.selectBuildHouseList(buildHouse);
  }

  @Override
  public List<BuildHouse> selectBuildHouseListByBuildingIds(List<Long> ids) {
    if (CollectionUtils.isEmpty(ids)) {
      return new ArrayList<>();
    }
    return buildHouseMapper.selectBuildHouseListByBuildingIds(ids);
  }

  /**
   * 新增房屋
   *
   * @param buildHouse 房屋
   * @return 结果
   */
  @Override
  public int insertBuildHouse(BuildHouse buildHouse) {
    buildHouse.setCreateTime(DateUtils.getNowDate());
    buildHouse.setUpdateTime(buildHouse.getCreateTime());
    buildHouse.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
    buildHouse.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
    return buildHouseMapper.insertBuildHouse(buildHouse);
  }

  @Override
  public int insertBuildHouses(List<BuildHouse> buildHouses) {
    if (CollectionUtils.isEmpty(buildHouses)) {
      return 1;
    }
    buildHouses.forEach(
        item -> {
          item.setCreateTime(DateUtils.getNowDate());
          item.setUpdateTime(item.getCreateTime());
          item.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
          item.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        });
    return buildHouseMapper.insertBuildHouses(buildHouses);
  }

  /**
   * 修改房屋
   *
   * @param buildHouse 房屋
   * @return 结果
   */
  @Override
  public int updateBuildHouse(BuildHouse buildHouse) {
    buildHouse.setUpdateTime(DateUtils.getNowDate());
    buildHouse.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
    return buildHouseMapper.updateBuildHouse(buildHouse);
  }

  /**
   * 删除房屋对象
   *
   * @param ids 需要删除的数据ID
   * @return 结果
   */
  @Override
  public AjaxResult deleteBuildHouseByIds(String ids) {
    List<String> houseIds = Arrays.asList(Convert.toStrArray(ids));
    for (String houseId : houseIds) {
      // 判断是否存在用户和房屋绑定
      BuildHouseUser buildHouseUser = new BuildHouseUser();
      buildHouseUser.setHouseId(Long.valueOf(houseId));
      List<BuildHouseUser> buildHouseUsers =
          buildHouseUserMapper.selectBuildHouseUserList(buildHouseUser);
      if (!buildHouseUsers.isEmpty()) {
        return AjaxResult.error("请先移除该房屋下的用户");
      }
    }
    int i = buildHouseMapper.deleteBuildHouseByIds(Convert.toStrArray(ids));
    return i > 0 ? AjaxResult.success() : AjaxResult.error();
  }

  /**
   * 删除房屋信息
   *
   * @param id 房屋ID
   * @return 结果
   */
  @Override
  public int deleteBuildHouseById(Long id) {
    return buildHouseMapper.deleteBuildHouseById(id);
  }

  @Override
  public List<BuildHouse> selectConditionBuildHouseList(BuildHouseSearchRequest request) {
    List<BuildHouse> buildHouses = buildHouseMapper.selectConditionBuildHouseList(request);
    if (buildHouses.isEmpty()) {
      return buildHouses;
    }
    List<Long> houseIds = buildHouses.stream().map(BuildHouse::getId).collect(Collectors.toList());
    List<User> users = buildHouseMapper.selectOwnerByHouseIds(houseIds);
    for (BuildHouse buildHouse : buildHouses) {
      User user =
          users.stream()
              .filter(e -> e.getHouseId().equals(buildHouse.getId()))
              .findFirst()
              .orElse(null);
      if (user != null) {
        buildHouse.setContactName(user.getUserName());
        buildHouse.setContactPhone(user.getPhone());
      } else {
        buildHouse.setContactName("");
        buildHouse.setContactPhone("");
      }
    }
    // 批量查询房屋的业主
    return buildHouses;
  }

  @Override
  public List<TenantStatisticDAO> selectTenantStatisticByBuilding(Long parkId) {
    return buildHouseMapper.selectTenantStatisticByBuilding(parkId);
  }

  @Override
  public List<HouseStatisticDAO> selectHouseStatisticByBuilding(Long parkId) {
    return buildHouseMapper.selectHouseStatisticByBuilding(parkId);
  }

  @Override
  public List<RentUserStatisticDAO> selectRentUserStatistic(RentStatisticRequest request) {
    return buildHouseMapper.selectRentUserStatistic(request);
  }

  @Override
  public List<RentHouseUserCountStatisticDAO> selectRentHouseUserCountStatisticByHouse(
      List<Long> houseIds) {
    if (CollectionUtils.isEmpty(houseIds)) {
      return new ArrayList<>();
    }
    return buildHouseMapper.selectRentHouseUserCountStatisticByHouse(houseIds);
  }

  @Override
  public List<FloorHouseDao> selectFloorHouseList(BuildHouse buildHouse) {

    return buildHouseMapper.selectFloorHouseList(buildHouse);
  }

  @Override
  public List<BuildHouse> batchSelectHouseByHouseCode(List<String> houseCodes) {
    return buildHouseMapper.batchSelectHouseByHouseCode(houseCodes);
  }

  @Override
  public List<SimpleHouseVo> areaBuildingHouseList(BuildHouseSearchRequest request) {
    return buildHouseMapper.areaBuildingHouseList(request);
  }

  @Override
  public List<AreaBuildingHouseVo> selecAreaBuildingHouseInfoByCondition(
      AreaBuildingHouseSearch search) {
    if (CollectionUtils.isEmpty(search.getHouseIds())) {
      return new ArrayList<>();
    }
    return buildHouseMapper.selecAreaBuildingHouseInfoByCondition(search);
  }

  @Override
  public IPage<BuildHouseV1> selectHousePageV1(HouseListSearch search) {

    QueryWrapper<BuildHouseV1> condition = new QueryWrapper<>();
    if (StringUtils.isNotNull(search.getParkId())) {
      condition.eq("park_id", search.getParkId());
    }
    if (StringUtils.isNotNull(search.getBuildingId())) {
      condition.eq("building_id", search.getBuildingId());
    }
    Page<BuildHouseV1> page = new Page<>();
    if (StringUtils.isNotNull(search.getPageNum()) && StringUtils.isNotNull(search.getPageSize())) {
      page.setCurrent(search.getPageNum());
      page.setSize(search.getPageSize());
    }
    condition.orderByAsc("create_time");
    return buildHouseMapperV1.selectPage(page, condition);
  }

  @Override
  public List<BuildHouseV1> selectHouseListV1(HouseListSearch search) {

    QueryWrapper<BuildHouseV1> condition = new QueryWrapper<>();
    if (StringUtils.isNotNull(search.getParkId())) {
      condition.eq("park_id", search.getParkId());
    }
    if (StringUtils.isNotNull(search.getBuildingId())) {
      condition.eq("building_id", search.getBuildingId());
    }
    if (StringUtils.isNotNull(search.getUserId())) {
      condition.eq("user_id", search.getUserId());
    }
    condition.orderByAsc("create_time");
    return buildHouseMapperV1.selectList(condition);
  }

  @Override
  public BuildHouseV1 selectBuildHouseV1(BuildHouseV1 buildHouseV1) {
    QueryWrapper<BuildHouseV1> condition = new QueryWrapper<>();
    if (StringUtils.isNotNull(buildHouseV1.getParkId())) {
      condition.eq("park_id", buildHouseV1.getParkId());
    }
    if (StringUtils.isNotNull(buildHouseV1.getBuildingId())) {
      condition.eq("building_id", buildHouseV1.getBuildingId());
    }
    if (StringUtils.isNotNull(buildHouseV1.getHouseCode())) {
      condition.eq("house_code", buildHouseV1.getHouseCode());
    }
    condition.eq("del_flag", "0");
    return buildHouseMapperV1.selectOne(condition);
  }
}
